<style lang="stylus" scoped>
.custom-link {
  padding: 20px 0;
  height: 400px;
}

.tabs {
  display: flex;
  border-bottom: 1px solid #e1e5eb;
  margin-bottom: 20px;
}

.tab {
  padding: 10px 20px;
  cursor: pointer;
  font-size: 14px;
  color: #666;
  border-bottom: 2px solid transparent;
  transition: all 0.3s;
  
  &.active {
    color: #4096ff;
    border-bottom-color: #4096ff;
    font-weight: 500;
  }
  
  &:hover {
    color: #1a7feb;
  }
}

.tab-content {
  display: none;
  
  &.active {
    display: block;
  }
}

.player-container {
  margin-top: 50px;
  height: 200px;
  width: 500px;

  padding: 20px;
  margin-bottom: 20px;
   display: flex;
  justify-content: center;
  align-items: center;
}




.search-section {
  margin-bottom: 20px;
  
  .search-input {
    width: 95%;
    padding: 10px 15px;
    border: 1px solid #e1e5eb;
    border-radius: 6px;
    font-size: 14px;
    
    &:focus {
      outline: none;
      border-color: #4096ff;
    }
  }
}

.search-results {
  max-height: 300px;
  overflow-y: auto;
  margin-top: 10px;
  
  .result-item {
    padding: 10px;
    border-bottom: 1px solid #f0f2f5;
    cursor: pointer;
    display: flex;
    align-items: center;
    
    &:hover {
      background: #000000;
    }
  }
  

  

}

.result-info {
  margin-left: 10px;
  flex: 1;

}

 .title-container {
    display: flex;
    justify-content: flex-end; 
    align-items: center;
    width: 100%; 
  }
  
  .title {
     font-size: 14px;
    color: #fff;
    margin-right: 15px; 
    white-space: nowrap; 
    overflow: hidden;
    text-overflow: ellipsis; 
  }
  
  .artist {
    font-size: 12px;
    color: #fff000;
  }
  
  .action-buttons {
    display: flex;
    gap: 8px;
      white-space: nowrap;
  }
  
  .play-btn, .download-btn {
    padding: 4px 8px;
    font-size: 12px;
    border-radius: 4px;
    border: none;
    cursor: pointer;
    background: #4096ff;
    color: white;
    
    &:hover {
      opacity: 0.9;
    }
  }
  
  .download-btn {
    background: #67c23a;
  }

</style>

<template>
  <div class="custom-link">
    <!-- 标签页导航 -->
    <div class="tabs">
      <div class="tab" :class="{ active: activeTab === 'player' }" @click="activeTab = 'player'">
        音乐播放
      </div>
      <div class="tab" :class="{ active: activeTab === 'search' }" @click="activeTab = 'search'">
        音乐搜索
      </div>
    </div>

    <!-- 播放器标签页 -->
    <div class="tab-content" :class="{ active: activeTab === 'player' }">
      <div class="player-container">
        <v-music class="music-player" progressColor="rgba(255, 255, 255, 1)" diskHW="110px" :musicList="musicList"
          :darkTheme="darkTheme" :offsetY="25" ref="player" @song-change="handleSongChange">

          <template #pause>
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
              <rect x="6" y="4" width="4" height="16" fill="currentColor" />
              <rect x="14" y="4" width="4" height="16" fill="currentColor" />
            </svg>
          </template>
          <template #play>
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M5 3L19 12L5 21V3Z" stroke="currentColor" stroke-width="2" stroke-linecap="round"
                stroke-linejoin="round" />
            </svg>
          </template>
        </v-music>
      </div>
    </div>

    <!-- 搜索标签页 -->
    <div class="tab-content" :class="{ active: activeTab === 'search' }">
      <div class="search-section">
        <input v-model="searchQuery" @keydown.enter="handleSearch" placeholder="搜索歌曲或艺术家..." class="search-input">
      </div>

      <div class="search-results">
        <div v-for="(item, index) in searchMusicList" :key="index" class="result-item" @click="selectSong(item)">
          <div class="result-info">
            <div class="title">{{ item.title }}-{{ item.artist || '未知艺术家' }}</div>
          </div>
          <div class="action-buttons">
            <button class="play-btn" @click.stop="searchPlaySongDirectly(item)">播放</button>
            <button class="download-btn" @click.stop="downloadSong(item)">下载</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { ref, computed } from 'vue';
import { Message } from '@/ui-lib/message/index';
import { Music } from '@database/entity/music';
import { musicApi } from '@/core/api/musicApi';
export default {
  emits: ['confirm'],
  components: {},
  props: {
    musicData: {
      type: Music,
      default() {
        return null;
      },
    },
  },
  setup(props, context) {
    const toolbars = ['bold', 'underline', 'italic', 'strikeThrough', 'title', 'sub', 'sup', 'quote', 'unorderedList', 'orderedList', 'codeRow', 'code', 'link', 'table', 'revoke', 'next', 'save', 'pageFullscreen', 'fullscreen', 'preview'];
    const paramsSeprator = '&&|&&';
    const title = ref(props.musicData.title);
    const artist = ref(props.musicData.artist);
    const musicId = ref(props.musicData.musicId);
    const activeTab = ref('player');
    const searchQuery = ref('');
    const currentSongIndex = ref(0);
    const player = ref(null);

    // 播放歌曲列表
    const musicList = ref([
      {
        title: '好运来',
        artist: '祖海',
        img: 'https://img.zhangpingguo.com/VAE_Article_ShouTu/vae/6802ac85-9f22-4cc4-b812-87238f103c36.jpg',
        src: 'https://img.zhangpingguo.com/music/%E7%A5%96%E6%B5%B7%20-%20%E5%A5%BD%E8%BF%90%E6%9D%A5.mp3',
        lyric: '[00:00.00]好运来-祖海\n[00:02.60]词：车行\n[00:05.20]曲：戚建波\n[00:07.80]好运来祝你好运来\n[00:11.19]\n[00:11.79]好运带来了喜和爱\n[00:16.15]好运来我们好运来\n[00:20.29]迎着好运兴旺发达通四海\n[00:24.78]\n[00:29.17]叠个千纸鹤再系个红飘带\n[00:32.72]\n[00:33.23]愿善良的人们天天好运来\n[00:37.36]你勤劳生活美你健康春常在\n[00:41.71]你一生的忙碌为了笑逐颜开\n[00:46.71]\n[00:47.36]打个中国结请春风剪个彩\n[00:51.40]愿祖国的日月年年好运来\n[00:55.56]你凤舞太平年你龙腾新时代\n[01:00.04]你幸福的家园迎来百花盛开\n[01:05.36]好运来祝你好运来\n[01:09.68]好运带来了喜和爱\n[01:13.91]好运来我们好运来\n[01:18.17]迎着好运兴旺发达通四海\n[01:24.22]\n[01:33.43]叠个千纸鹤再系个红飘带\n[01:37.46]愿善良的人们天天好运来\n[01:41.64]你勤劳生活美你健康春常在\n[01:46.00]你一生的忙碌为了笑逐颜开\n[01:50.95]\n[01:51.46]打个中国结请春风剪个彩\n[01:55.74]愿祖国的日月年年好运来\n[01:59.87]你凤舞太平年你龙腾新时代\n[02:04.18]你幸福的家园迎来百花盛开\n[02:09.62]好运来祝你好运来\n[02:14.05]好运带来了喜和爱\n[02:18.24]好运来我们好运来\n[02:22.52]迎着好运兴旺发达通四海\n[02:26.74]好运来祝你好运来\n[02:31.10]好运带来了喜和爱\n[02:35.35]好运来我们好运来\n[02:39.63]迎着好运兴旺发达通四海\n[02:45.09]\n[02:59.12]好运来祝你好运来\n[03:03.26]好运带来了喜和爱\n[03:07.43]好运来我们好运来\n[03:11.68]迎着好运兴旺发达通四海\n[03:16.02]通四海好运来'
      }
    ]);

    // 搜索歌曲列表
    const searchMusicList = ref([]);

    // 主题
    const darkTheme = ref(true);

    // 过滤后的音乐列表
    const filteredMusicList = computed(() => {
      if (!searchQuery.value) return musicList.value;
      const query = searchQuery.value.toLowerCase();
      return musicList.value.filter(item =>
        item.title.toLowerCase().includes(query) ||
        (item.artist && item.artist.toLowerCase().includes(query))
      );
    });

    // 搜索处理
    const handleSearch = () => {
      musicApi().searchMp3({ musicName: searchQuery.value }).then((res) => {
        if (res.code == 200) {
          searchMusicList.value = res.data
        } else {
          new Message({ message: res.message });
        }
      }).catch((e) => {
        new Message({ message: e.message || '请求失败，请重试' });
      });
    };

    // 选择歌曲
    const selectSong = (song) => {
      const index = musicList.value.findIndex(item => item.title === song.title);
      if (index !== -1) {
        playSong(index);
        activeTab.value = 'player'; // 切换到播放器标签
      }
    };

    // 播放歌曲
    const playSong = (index) => {
      currentSongIndex.value = index;
      if (player.value) {
        player.value.play(index);
      }
    };


    // 歌曲变化处理
    const handleSongChange = (index) => {
      currentSongIndex.value = index;
    };

    // 直接播放歌曲
    const searchPlaySongDirectly = async (song) => {
      try {
        const res = await musicApi().getMp3({ musicId: song.musicId })
      
        musicList.value  = [{
          title: res.data.title,
          artist: res.data.artist,
          img:res.data.coverUrl,
          src: res.data.mp3Url,
          lyric: res.data.lrcContent
        }]

      } catch (error) {
        console.error('搜索歌曲失败:', error);
      }

        activeTab.value = 'player'


    };

    // 下载歌曲
    const downloadSong = (song) => {
      musicApi().getMp3({ musicId: song.musicId }).then((res) => {
        if (res.code == 200) {
          window.open(res.data.mp3Url, '_blank')
        } else {
          new Message({ message: res.message });
        }
      }).catch((e) => {
        new Message({ message: e.message || '请求失败，请重试' });
      });
    };


    const confirm = () => {
      const numberMatch = title.value.match(/# (.+)/);
      title.value = numberMatch ? numberMatch[1] : title.value.substring(0, 5);
      context.emit('confirm', {
        undercoat: title,
        value: `music:${title.value}${paramsSeprator}${artist.value}${paramsSeprator}${musicId.value}`,
      });
    };

    return {
      title,
      artist,
      musicId,
      toolbars,
      darkTheme,
      musicList,
      searchMusicList,
      activeTab,
      searchQuery,
      filteredMusicList,
      currentSongIndex,
      player,
      searchPlaySongDirectly,
      downloadSong,
      handleSearch,
      selectSong,
      playSong,
      handleSongChange,
      confirm
    };
  },
};
</script>